<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------
use think\Image;
use think\Db;
use think\Hook;
// 应用公共文件
/**
 * 得到混淆福字符串，长度10
 * @return [type] [10位字符串]
 */
function get_mix(){
	$str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
	$mix = substr(str_shuffle($str),0,10);
	return $mix;
}
/**
 * 加密密码
 * @param  [type] $mix [description]
 * @param  [type] $pwd [description]
 * @return [type]      [description]
 */
function get_password($mix,$pwd){
   return md5(md5($mix.$pwd));

}
/**
 * 生成验证签名
 * @param  [type] $data [数组]
 * @return [type]       [签名数据]
 */
function get_signature($data){
	//先进行字典排序
    sort($data);
    //key-v拼接
    $str = '';
    foreach($data as $k => $v){
    	$str .= ($k.'='.$v.'&');
    }
    $restr = sha1($str);
    return $restr;
}
/**
 * 验证签名
 * @param  [type] $data      [description]
 * @param  [type] $signature [description]
 * @return [type]            [description]
 */
function check_signature($data,$signature){
     //先进行字典排序
    sort($data);
    //key-v拼接
    $str = '';
    foreach($data as $k => $v){
    	$str .= ($k.'='.$v.'&');
    }
    $restr = sha1($str);
    if($restr == $signature){
    	return true;
    }else{
    	return false;
    }
}
/**
 * 得到头像
 * @param  [type] $imgUrl [description]
 * @return [type]         [description]
 */
function get_avatar($imgUrl){
	if(!$imgUrl){
       $imgUrl = config('view_replace_str.__STATIC__').'/admin/avatars/user.jpg';
	}
	return $imgUrl;
}
/**
 * 单位转换
 * @param  [type] $bite [字节]
 * @return [type]       [description]
 */
function unit_converter($bite){
    if($bite < 1024){
        $res = $bite.'字节';
    }else{
        $int = $bite/1024;
        if(intval($int) < 1024){
            $res = number_format($int,2).'KB';
        }else{
            $int = $bite/(1024*1024);
            $res = number_format($int,2).'M';
        }
    }
    return $res;
}
/**
 * 设置到配置文件
 * @param [type] $key [description]
 * @param [type] $data [description]
 */
function set_config($key,$data){
  if(file_exists(HBBCMS_DIR.'/data/config/config.php')){
     $config = include HBBCMS_DIR.'/data/config/config.php';
  }
  $config[$key] = $data;
  if(file_put_contents(HBBCMS_DIR.'/data/config/config.php', "<?php \r\n return ".var_export($config,true).";")){
    return true;
  }else{
      return false;
  }
}
/**
 * 获取配置
 * @param  [type] $key [description]
 * @return [type]      [description]
 */
function get_config($key){
   return config($key)?config($key):'';
}
/**
 * 下载文件
 * @param  [type] $filepath [description]
 * @return [type]           [description]
 */
function down_file($filepath){
    header('Content-Description: File Transfer');
    header('Content-Type: application/octet-stream');
    header('Content-Disposition: attachment; filename='.basename($filepath));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($filepath));
    readfile($filepath);
}
/**
 * 图片上传
 * @param  [type]  $file       [文件]
 * @param  [type]  $path       [保存目录]
 * @param  boolean $thumb      [是否由缩略图]
 * @param  boolean $water      [是否由水印]
 * @param  string  $water_type [1：图片水印，0：文字水印]
 * @return [type]              [图片地址]
 */
function upload_img($file,$path,$thumb = false,$water = false,$water_type="1"){
    $validate = [
        'size' => config('web_upload.img_max_size')*1024,
        'ext'  => config('web_upload.img_allow_suf'),
    ];
    $dir = config('web_upload.upload_path').'/'.$path ;
    if(!is_dir($dir)){
       mkdir($dir,0777,true);
    }
    $info = $file->validate( $validate )->move($dir);
    if($info){
         $res = [];
         $filename = str_replace('\\','/',$dir.'/'.$info->getSaveName());
        //缩略图
        if($thumb){
           $file_thumb_extends = strstr($filename,$info->getFilename(),true);
           $image = Image::open($file);
           $thumb_min_width = config('web_upload.thumb_min_width');
           $thumb_min_height = config('web_upload.thumb_min_height');
           $thumb_mid_width = config('web_upload.thumb_mid_width');
           $thumb_mid_height = config('web_upload.thumb_mid_height');
           $thumb_max_width = config('web_upload.thumb_max_width');
           $thumb_max_height = config('web_upload.thumb_max_height');
           $filename_thumb_mix = $file_thumb_extends.'thumb_'.$thumb_min_width.'_'.$info->getFilename();
           $filename_thumb_mid = $file_thumb_extends.'thumb_'.$thumb_mid_width.'_'.$info->getFilename();
           $filename_thumb_max = $file_thumb_extends.'thumb_'.$thumb_max_width.'_'.$info->getFilename();
           $image->thumb($thumb_max_width, $thumb_max_height)->save($filename_thumb_max);
           $image->thumb($thumb_mid_width, $thumb_mid_height)->save($filename_thumb_mid);
           $image->thumb($thumb_min_width, $thumb_min_height)->save($filename_thumb_mix);
           $res['thumb'] = $filename_thumb_mix.','.$filename_thumb_mid.','.$filename_thumb_max;
        }
        //水印
        if($water){
            $image = Image::open($file);
            $water_palce = config('web_upload.water_place');
            $water_alpha = config('web_upload.water_alpha');
            if($water_type == 1){
               $image->water(config('web_upload.water_img'),$water_palce,$water_alpha)->save($filename);
            }else{
               $image->text('hbbcms','./vendor/topthink/think-captcha/assets/ttfs/6.ttf',20,'#ffffff',$water_palce,-20)->save($filename);
            } 
        }
        $res['filename'] = $filename;
        $res['success'] = '1';
    }else{
       $res = ['success' => 0,
               'msg'     => $file->getError()
       ];
    }
      return $res;
}
function get_img($url){
   if($url){
      $res = "__ROOT__/".$url;
   }else{
      $res = "__STATIC__/hbb/image/nopic.jpg";
   }
   return $res;
}
/**
 * 时间格式化
 * @return [type] [description]
 */
function get_time_format($time,$date = true){
      $mtime=time()-$time;
      if($mtime<=60){
         $res = $mtime.'秒前';
      }else if($mtime>60 && $mtime<3600){
         $res  =round($mtime/60).'分前';
      }else if($mtime>=3600 && $mtime<3600*24){
         $res  =round($mtime/3600).'小时前';
      }else if($mtime>=3600*24 && $mtime<3600*24*2){
         $res  ='一天前';
      }else if($mtime>=3600*24*2 && $mtime<3600*24*3){
         $res  ='两天前';
      }else if($mtime>=3600*24*3 && $mtime<3600*24*4){
         $res  ='三天前';
      }else{
        if($date){
          $res  =date('Y-m-d H:i',$time);
        }else{
           $res  =date('Y-m-d',$time);
        }
      }
      return $res;
}
/**
 * 执行文件中SQL语句函数
 * @param string $file sql语句文件路径
 * @param string $prefix  自己的前缀
 * @return multitype:string 返回最终需要的sql语句
 */

function execute_file_sql($file, $prefix='') {
    $sql_data = file_get_contents($file);
    if (!$sql_data) {
        return false;
    }
    $sql_format = sql_split($sql_data, $prefix);
    $counts = count($sql_format);
    for ($i = 0; $i < $counts; $i++) {
        $sql = trim($sql_format[$i]);
        try {
            Db::execute($sql);
        } catch (\Exception $e) {
            throw new \think\Exception($e);
        }
        
    }
    return true;
}

/**
 * 解析数据库语句函数
 * @param string $sql  sql语句   带默认前缀的
 * @param string $prefix  自己的前缀
 * @return multitype:string 返回最终需要的sql语句
 */
function sql_split($sql, $prefix='') {

    $r_tablepre = config('database.prefix');
    if ($r_tablepre != $prefix) {
        $sql          = str_replace( $r_tablepre, $prefix , $sql);
    }

    $sql = preg_replace("/TYPE=(InnoDB|MyISAM|MEMORY)( DEFAULT CHARSET=[^; ]+)?/", "ENGINE=\\1 DEFAULT CHARSET=utf8", $sql);

    $sql          = str_replace("\r", "\n", $sql);
    $ret          = array();
    $num          = 0;
    $queriesarray = explode(";\n", trim($sql));
    unset($sql);
    foreach ($queriesarray as $query) {
        $ret[$num] = '';
        $queries   = explode("\n", trim($query));
        $queries   = array_filter($queries);
        foreach ($queries as $query) {
            $str1 = substr($query, 0, 1);
            if ($str1 != '#' && $str1 != '-') {
                $ret[$num] .= $query;
            }

        }
        $num++;
    }
    
    return $ret;
}
/**
 * 列出本地目录的文件
 * @param string $path
 * @param string $pattern
 * @return array
 */
function list_file($path, $pattern = '*'){
    if (strpos($pattern, '|') !== false) {
        $patterns = explode('|', $pattern);
    } else {
        $patterns [0] = $pattern;
    }
    $i = 0;
    $dir = array();
    if (is_dir($path)) {
        $path = rtrim($path, '/') . '/';
    }
    foreach ($patterns as $pattern) {
        $list = glob($path . $pattern);
        if ($list !== false) {
            foreach ($list as $file) {
                $dir [$i] ['filename'] = basename($file);
                $dir [$i] ['path'] = dirname($file);
                $dir [$i] ['pathname'] = realpath($file);
                $dir [$i] ['owner'] = fileowner($file);
                $dir [$i] ['perms'] = substr(base_convert(fileperms($file), 10, 8), -4);
                $dir [$i] ['atime'] = fileatime($file);
                $dir [$i] ['ctime'] = filectime($file);
                $dir [$i] ['mtime'] = filemtime($file);
                $dir [$i] ['size'] = filesize($file);
                $dir [$i] ['type'] = filetype($file);
                $dir [$i] ['ext'] = is_file($file) ? strtolower(substr(strrchr(basename($file), '.'), 1)) : '';
                $dir [$i] ['isDir'] = is_dir($file);
                $dir [$i] ['isFile'] = is_file($file);
                $dir [$i] ['isLink'] = is_link($file);
                $dir [$i] ['isReadable'] = is_readable($file);
                $dir [$i] ['isWritable'] = is_writable($file);
                $i++;
            }
        }
    }
    $cmp_func = create_function('$a,$b', '
    if( ($a["isDir"] && $b["isDir"]) || (!$a["isDir"] && !$b["isDir"]) ){
      return  $a["filename"]>$b["filename"]?1:-1;
    }else{
      if($a["isDir"]){
        return -1;
      }else if($b["isDir"]){
        return 1;
      }
      if($a["filename"]  ==  $b["filename"])  return  0;
      return  $a["filename"]>$b["filename"]?-1:1;
    }
    ');
    usort($dir, $cmp_func);
    return $dir;
}
/**
 * 删除文件夹
 * @param string
 * @param int
 */
function remove_dir($dir, $time_thres = -1){
    foreach (list_file($dir) as $f) {
        if ($f ['isDir']) {
            remove_dir($f ['pathname'] . '/');
        } else if ($f ['isFile'] && $f ['filename']) {
            if ($time_thres == -1 || $f ['mtime'] < $time_thres) {
                @unlink($f ['pathname']);
            }
        }
    }
    return true;
}